package com.yonyou.gmmc.service.shopping.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.gmmc.common.annotation.ParamValid;
import org.marketing.common.Response;
import com.yonyou.gmmc.service.shopping.constant.ShoppingConstant;
import com.yonyou.gmmc.service.shopping.model.AddressPo;
import com.yonyou.gmmc.service.shopping.model.AddressTreePo;
import com.yonyou.gmmc.service.shopping.model.ReceiveAdd;
import com.yonyou.gmmc.service.shopping.model.TmTpAddress;
import com.yonyou.gmmc.service.shopping.model.TmTpReceiveAdd;
import com.yonyou.gmmc.service.shopping.service.ReceiveAddService;
import com.yonyou.gmmc.service.shopping.service.ShoppingOrderService;

import io.swagger.annotations.ApiOperation;

/**
 * @author Administrator
 * @date 2017年3月8日
 */
@RestController
@RequestMapping(value = ShoppingConstant.BASE_PATH + "/" + ShoppingConstant.VERSION)
public class ReceiveAddController {
	private Logger logger = Logger.getLogger(ReceiveAddController.class);

	@Autowired
	private ReceiveAddService receiveAddService;

    @Autowired
    private ShoppingOrderService shoppingOrderService;
    
	/**
	 * 获取收货地址
	 */
	@RequestMapping(value = "/getReceiveAdd", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "获取收货地址", notes = "获取收货地址")
	public Response getReceiveAdd(HttpServletRequest request) {
		String openId = request.getHeader(CommonConstant.HEADER_OPENID);
        if(CheckUtil.NullOrEmpty(openId)){
        	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
        	if(!CheckUtil.NullOrEmpty(userId)){
        		openId = shoppingOrderService.selectopenIdByUserId(userId);
        	}
        }
		try {
			List<ReceiveAdd> receiveAddList = receiveAddService.getReceiveAdd(openId);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, receiveAddList, "");
		} catch (Exception e) {
			logger.error("获取收货地址发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 获取所有地址
	 */
	@RequestMapping(value = "/getAllAddress", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "获取所有京东地址", notes = "获取所有京东地址")
	public Response getAllAddress() {

		try {
			List<AddressPo> addressList = receiveAddService.selectAllAdd();

			Map<String, AddressTreePo> tempMap = new HashMap<>();
			Map<String, Object> resultMap = new HashMap<>();

			for (int n = 0; n < addressList.size(); n++) {
				AddressTreePo addressTree = new AddressTreePo();
				addressTree.setAddressCode(addressList.get(n).getAddressCode());
				addressTree.setAddressName(addressList.get(n).getAddressName());
				addressTree.setParentCode(addressList.get(n).getParentCode());
				addressTree.setRankType(addressList.get(n).getRankType());
				tempMap.put(addressList.get(n).getAddressCode().toString(), addressTree);
			}

			for (Map.Entry<String, AddressTreePo> entry : tempMap.entrySet()) {
				if (null != entry.getValue().getParentCode()) {
					AddressTreePo rt = tempMap.get(entry.getValue().getParentCode().toString());
					if (rt != null) {

						tempMap.get(entry.getValue().getParentCode().toString()).getChildren().add(entry.getValue());

					}
				}
			}

			for (Map.Entry<String, AddressTreePo> entry : tempMap.entrySet()) {
				if (null == entry.getValue().getParentCode()) {
					resultMap.put(entry.getValue().getAddressCode().toString(), entry.getValue());
				}
			}

			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, resultMap, "");
		} catch (Exception e) {
			logger.error("获取所有地址异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}

	}

	/**
	 * 根据parentCode获取地址
	 */
	@RequestMapping(value = "/getAddByCode", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "获取京东地址", notes = "获取京东地址")
	public Response getAddByCode(@RequestParam String parentCode) {
		try {
			List<TmTpAddress> tmTpAddressList = receiveAddService.getAddByCode(parentCode);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, tmTpAddressList, "");
		} catch (Exception e) {
			logger.error("获取地址异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	/**
	 * 保存收货地址
	 * 
	 * @param receiveAdd
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveReceiveAdd", method = RequestMethod.POST)
	@ApiOperation(value = "保存收货地址信息", notes = "保存收货地址信息")
	@ParamValid
	public Response saveReceiveAdd(@RequestBody TmTpReceiveAdd tmTpReceiveAdd, HttpServletRequest request) {
		String openId = request.getHeader(CommonConstant.HEADER_OPENID);
        if(CheckUtil.NullOrEmpty(openId)){
        	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
        	if(!CheckUtil.NullOrEmpty(userId)){
        		openId = shoppingOrderService.selectopenIdByUserId(userId);
        	}
        }
		try {
			Map<String, Object> result = receiveAddService.saveReceiveAdd(tmTpReceiveAdd, openId);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, result, "");
		} catch (Exception e) {
			logger.error("保存状态发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

	@RequestMapping(value = "/selectOrderAddress", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "查询订单详情收货人地址", notes = "查询订单详情收货人地址")
	@ParamValid
	public Response selectOrderAddress(@RequestParam(required = true, defaultValue = "") String thirdOrder,
			HttpServletRequest request) {
		String openId = request.getHeader(CommonConstant.HEADER_OPENID);
        if(CheckUtil.NullOrEmpty(openId)){
        	String userId = request.getHeader(CommonConstant.HEAD_USER_ID);
        	if(!CheckUtil.NullOrEmpty(userId)){
        		openId = shoppingOrderService.selectopenIdByUserId(userId);
        	}
        }
		// String openId = "oXrcfuGP_a3daNZaMT_rbhvJ595I";
		// String openId = "oXrcfuD2cXUtN56eT_wcH19L9nNQ";
		try {
			List<ReceiveAdd> orderAddressList = receiveAddService.selectOrderAddress(thirdOrder, openId);
			return new Response<>(ResultMsgConstants.RESULT_CODE_SUCCESS, orderAddressList, "");
		} catch (Exception e) {
			logger.error("获取收货地址发生异常", e);
			return new Response<>(ResultMsgConstants.RESULT_CODE_ERROR, e.getMessage());
		}
	}

}
